# Copyright (c) 2018 Presto Labs Pte. Ltd.
# Author: inkyu

import datetime
import json
import logging

from tornado import gen, httpclient, ioloop
from coin.base.timestamp import get_timestamp


# TODO(inkyu): Move to somewhere & refactor
class BasisReceiver(object):
  def __init__(self, ioloop):
    self._logger = logging.getLogger(__name__)
    self._ioloop = ioloop
    self._period = datetime.timedelta(seconds=1)
    self._stopped = False
    self._querying = False
    self._url = 'http://localhost:8080/api/hk_group'
    self.basis = None
    self.timestamp = None

  def _on_timeout(self):
    if self._stopped:
      return
    if not self._querying:
      self._ioloop.add_callback(self._run_query)
    else:
      self._logger.warning('Still qeurying. Skip querying this time')
    self._ioloop.add_timeout(self._period, self._on_timeout)

  def start(self):
    self._ioloop.add_timeout(self._period, self._on_timeout)

  def get_basis(self, bid_ask, exchange_a, exchange_b, product, window_size):
    basis_symbol = product.native_symbol.replace('USDT', 'USD')
    basis_key = 'hk_group.%s.%s.%s_price_1m,hk_group.%s.%s.%s_price_1m' % (
        exchange_a, basis_symbol, bid_ask, exchange_b, basis_symbol, bid_ask)
    if self.basis is None:
      return (None, None)
    if basis_key in self.basis:
      basis = self.basis[basis_key]['basis']
      if str(window_size) in basis.keys():
        basis_data = basis[str(window_size)]
        if True or basis_data['ready']:
          coverage = basis_data['coverage']
          value = basis_data['value']
          last_fetched_time = basis_data['last_fetched_time_sec']
          return (value, last_fetched_time)
        else:
          self._logger.warning('Basis is not ready: %s' % basis_data)
      else:
        self._logger.warning('Could not find basis window: %s' % window_size)
    else:
      self._logger.warning('Could not find basis data: %s' % basis_key)
    return (None, None)

  @gen.coroutine
  def _run_query(self):
    self._querying = True
    try:
      client = httpclient.AsyncHTTPClient()
      response = yield client.fetch(self._url)
      msg = json.loads(response.body)
      self.basis = msg['basis']
      self.timestamp = get_timestamp()
    except httpclient.HTTPError:
      self._logger.exception('Query error')
    finally:
      self._querying = False


if __name__ == '__main__':
  io_loop = ioloop.IOLoop.instance()
  BasisReceiver(io_loop).start()
  io_loop.start()
